import { NextRequest, NextResponse } from 'next/server';

// 后端API基础URL
const UPSTREAM = 'http://localhost:3000/api';

export async function POST(req: NextRequest) {
  try {
    // 获取请求体
    const body = await req.json();
    
    // 构建目标URL
    const target = `${UPSTREAM}/auth/refresh-token`;
    console.log('刷新令牌请求代理到：', target);
    
    // 调用上游API，设置必要的头信息
    const upstream = await fetch(target, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
      },
      body: JSON.stringify(body)
    });
    
    // 获取上游响应
    const responseData = await upstream.json();
    
    // 创建响应，添加CORS头
    return NextResponse.json(responseData, {
      status: upstream.status,
      headers: {
        'Access-Control-Allow-Origin': '*',
        'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
        'Access-Control-Allow-Headers': 'Content-Type, Authorization',
        'Access-Control-Allow-Credentials': 'true'
      }
    });
  } catch (error) {
    console.error('刷新令牌请求代理失败:', error);
    return NextResponse.json(
      { error: '刷新令牌失败，请稍后重试' },
      { status: 500 }
    );
  }
}

export async function OPTIONS() {
  return NextResponse.json({}, {
    headers: {
      'Access-Control-Allow-Origin': '*',
      'Access-Control-Allow-Methods': 'POST, OPTIONS',
      'Access-Control-Allow-Headers': 'Content-Type, Authorization',
      'Access-Control-Allow-Credentials': 'true'
    }
  });
}